//
//  VersionManager.swift
//  MobileRTCSwiftSample
//
//  Created by zhangheng on 2019/6/11.
//  Copyright © 2019 Zoom Video Communications, Inc. All rights reserved.
//


struct VersionInfo {
    var url: String?             //下载应用URL
    var title: String?           //title
    var message: String?         //提示内容
    var must_update: Bool?       //是否强制更新
    var version: String?         //版本
}

class VersionManager: NSObject {
    
    //本地版本
    static func localVersion() -> String? {
        return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
    }
    
    //
    static func versionUpdate(info:VersionInfo) {
        //1 请求服务端数据，并进行解析,得到需要的数据
        //2 版本更新
        let defaultmsg = "⭐️⭐️修复已知的BUG."//"提示更新内容，解决了xxx等一系列问题，新增了xxx等功能！\n提示更新内容，解决了xxx等一系列问题\n新增了xxx等功能！"//
        let defaultVersion = "3.5"
        let newmsg = (info.message==nil||info.message=="") ? defaultmsg:info.message!
        let newversion = info.version==nil ? defaultVersion:info.version!
        let upUrl = info.url==nil ? mt_url_appstore:info.url!
        let t = info.title==nil ? "有新版本啦".localized():info.title!
        let must = info.must_update==nil ? false:info.must_update!
        handleUpdate(VersionInfo(url: upUrl , title: t, message: newmsg, must_update: must, version: newversion))
    }
    
    /// 版本更新
    private static func handleUpdate(_ info: VersionInfo) {
        guard let localVersion = localVersion()else { return }
        if isIgnoreCurrentVersionUpdate(info.version!) { return }
        if versionCompare(localVersion: localVersion, serverVersion: info.version!) {
            Dialog.shared.showUpdata(title: info.title,version:info.version, msg: info.message) {
                //NSWorkspace.shared.open(NSURL(string:info.url)! as URL)
                UpdateEngine.shared.loadying(url:info.url)
            }
            
        }
    }
    
    // 版本比较
    private static func versionCompare(localVersion: String, serverVersion: String) -> Bool {
        let result = localVersion.compare(serverVersion, options: .numeric, range: nil, locale: nil)
        if result == .orderedDescending || result == .orderedSame{
            return false
        }
        return true
    }
    
    // 是否忽略当前版本更新
    private static func isIgnoreCurrentVersionUpdate(_ version: String) -> Bool {
        return false//UserDefaults.standard.string(forKey: "IgnoreCurrentVersionUpdate") == version
    }
}


